package com.xiyou.week04.dfs;

/**
 * 130. 被围绕的区域
 *
 * @ClassName：Solve
 * @Author：西柚
 * @Date：2022/1/23 7:45 下午
 * @Versiion：1.0
 */
public class Solve {

    int row, col;
    int[] dx = {-1, 0, 0, 1};
    int[] dy = {0, -1, 1, 0};

    public void solve(char[][] board) {
        if (board == null || board.length == 0 || board[0] == null || board[0].length == 0) {
            return;
        }
        row = board.length;
        col = board[0].length;

        for (int i = 0; i < row; i++) {
            dfs(board, i, 0);
            dfs(board, i, col - 1);
        }
        for (int i = 0; i < board.length; i++) {
            System.out.println(String.valueOf(board[i]));
        }

        for (int i = 0; i < col; i++) {
            dfs(board, 0, i);
            dfs(board, row - 1, i);
        }
        for (int i = 0; i < board.length; i++) {
            System.out.println(String.valueOf(board[i]));
        }

        for (int i = 0; i < row; i++) {
            for (int j = 0; j < col; j++) {
                if (board[i][j] == 'O') {
                    board[i][j] = 'X';
                } else if (board[i][j] == 'Y') {
                    board[i][j] = 'O';
                }
            }
        }
    }

    private void dfs(char[][] board, int i, int j) {
        if (i < 0 || i >= col || j < 0 || j >= row || board[i][j] != 'O') {
            return;
        }
        board[i][j] = 'Y';

        for (int k = 0; k < 4; k++) {
            int nx = i + dx[k];
            int ny = j + dy[k];
            dfs(board, nx, ny);
        }
    }

    public static void main(String[] args) {
        Solve solve = new Solve();
//        char[][] board = new char[][]{
//                {'X', 'X', 'X', 'X'},
//                {'X', 'O', 'O', 'X'},
//                {'X', 'X', 'O', 'X'},
//                {'X', 'O', 'X', 'X'}
//        };
        char[][] board = new char[][]{
                {'X', 'O', 'X'},
                {'O', 'X', 'O'},
                {'X', 'O', 'X'}
        };
        solve.solve(board);
        for (int i = 0; i < board.length; i++) {
            System.out.println(String.valueOf(board[i]));
        }
    }

}
